package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.vo.SocilaUser;
import com.atguigu.gulimall.gulimallthirdparty.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")//请求参数会问号带一个 code
    public String weibo(@RequestParam("code") String code) throws Exception {
        //根据code换accessToken
        Map<String,String> map = new HashMap<>();
        map.put("client_id","1683858653");
        map.put("client_secret","163f4ab730c8cc7184becf643ea5e6ff");
        map.put("grant_type","authorizatipn_code");
        map.put("redirect_uri","http://gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        HttpResponse response = HttpUtils.doPost("api.weibo.com", "/aouth/access_token", "post", null, null, map);
        //登录成功跳到首页
        //响应状态码 如果==200就成功
        if (response.getStatusLine().getStatusCode()==200){
            //响应实体，是json，转对象
            //拿到响应内容 变成String
            String json = EntityUtils.toString(response.getEntity());
            //转对象
            SocilaUser socilaUser = JSON.parseObject(json, SocilaUser.class);
            //给当前社交用户生成会员信息账号，以后就关联这个用户
            R r = memberFeignService.oauth2(socilaUser);
            if (r.getCode()==0){
                //成功
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功，用户信息："+data);
                return "redirect://gulimall.com";
            }else {
                return "redirect://auth.gulimall.com/login.html";
            }
        }else {
            //没获取到 重定向到登录页 登录失败
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
